package net.techwatch.fsindex;

import java.io.File;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import net.techwatch.fsindex.dao.FileSystemDao;
import net.techwatch.fsindex.event.FileSystemEvent;

/**
 * @author wiv
 *
 */
@SuppressWarnings("unchecked")
public abstract class FileSystemChecker implements Runnable {
	
	/**
	 * 
	 */
	private CountDownLatch countDown;
	
	/**
	 * 
	 */
	private FileSystemMonitor monitor;
	
	private List fileSystemObjectList;
	
	/**
	 * 
	 */
	private FileSystemDao dataManager;
	
	/**
	 * Default constructor
	 */
	public FileSystemChecker() {
		// nothing to do
	}
	
	public List getFileSystemLObjectList() {
		return this.fileSystemObjectList;
	}
	
	public void setFileSystemObjectList(List fileSystemObjectList) {
		this.fileSystemObjectList = fileSystemObjectList;
	}
	
	public CountDownLatch getCountDownLatch() {
		return countDown;
	}
	
	public void setCountDownLatch(CountDownLatch countDown) {
		this.countDown = countDown;
	}
	
	public FileSystemMonitor getFileSystemMonitor() {
		return monitor;
	}
	
	public void setFileSystemMonitor(FileSystemMonitor monitor) {
		this.monitor = monitor;
	}
	
	/**
	 * @param dataManager
	 */
	public void setFileSystemDataManager(FileSystemDao dataManager) {
		this.dataManager = dataManager;
	}
	
	/**
	 * @return
	 */
	public FileSystemDao getFileSystemDataManager() {
		return this.dataManager;
	}
	
	/**
	 * @param fsObj
	 */
	protected void checkForDeletion(FileSystemObject fsObj) {
		if(!new File(fsObj.getPath()).exists()) {
			FileSystemEvent event = new FileSystemEvent(this);
			event.setFile(fsObj.isFile());
			event.setId(fsObj.getId());
			event.setLastUpdate(fsObj.getLastUpdate());
			event.setParentPath(fsObj.getPath().substring(0, fsObj.getPath().lastIndexOf("/")));
			event.setName(fsObj.getPath().substring(fsObj.getPath().lastIndexOf("/") + 1));
			
			// post event for delete
			monitor.postDelete(event);
		}
	}
	
	/**
	 * @param fsObj
	 * @return
	 */
	protected boolean checkForUpdate(FileSystemObject fsObj) {
		long lastUpdate = new File(fsObj.getPath()).lastModified();
		
		if(fsObj.getLastUpdate() < lastUpdate) {
			FileSystemEvent event = new FileSystemEvent(this);
			event.setFile(fsObj.isFile());
			event.setId(fsObj.getId());
			event.setLastUpdate(lastUpdate);
			event.setParentPath(fsObj.getPath().substring(0, fsObj.getPath().lastIndexOf("/")));
			event.setName(fsObj.getPath().substring(fsObj.getPath().lastIndexOf("/") + 1));
			
			// post event for update
			monitor.postUpdate(event);
			
			return true;
		}
		
		return false;
	}

}
